<?php

namespace app\app\controller\v1;
use think\Db;
use think\Request;
use app\app\util\OnlineUtils;

require_once(dirname(dirname(dirname(__FILE__))).'/util/phpqrcode/phpqrcode.php');
use phpqrcode\QRcode;

class CardController extends BaseController{

   /**
     * 显示资源列表
     * 我的名片列表
     * @return \think\Response
     */
    public function index()
    {
        $user_id = OnlineUtils::getUserIdBySid();
        $card = Db::query('select a.id,a.name,a.user_id,a.phone,a.email,a.company_name,a.position,a.module_id,b.wx_nick_name,b.portrait,a.introduce,a.pv,a.collect,a.click from hmp_card a left join hmp_users b on a.user_id=b.id where a.user_id= '.$user_id.' and a.status=1 and b.status=1 order by a.id desc');
        if($card){

        }else{
            $card = [];
        }
        //查询出优惠券
        $coupon = Db::name('coupon')->field('id,title,price,num,lnt,lgt,description')->where('user_id','eq',$user_id)->select();
        return hmp(200,'success',['data'=>$card,'coupon'=>$coupon]);
    }

    /**
     * 显示创建资源表单页.
     *
     * @return \think\Response
     */
    public function create()
    {

    }

    /**
     * 保存新建的资源
     * 点赞
     * @param  \think\Request  $request
     * @return \think\Response
     */
    public function save()
    {
        $user_id = OnlineUtils::getUserIdBySid();     
        //新增
        $card['name']         = input('post.name') ? input('post.name') : '';
        $card['phone']        = input('post.phone') ? input('post.phone') : '';
        $card['company_name'] = input('post.company_name') ? input('post.company_name') : '';
        $card['address']      = input('post.address') ? input('post.address') : '';
        $card['email']        = input('post.email') ? input('post.email') : '';
        $card['keyword']      = input('post.keyword') ? input('post.keyword') : '';
        $card['introduce']    = input('post.introduce') ? input('post.introduce') : '';
        $card['module_id']    = input('post.module_id') ? input('post.module_id') : '';
        $card['activity']     = input('post.activity') ? input('post.activity') : '';
        $card['user_id']      = $user_id;
        $card['position']     = input('post.position') ? input('post.position') : '';
        $card['wx_number']    = input('post.wx_number') ? input('post.wx_number') : '';
		$card['img_desc']     = input('post.img_desc') ? input('post.img_desc') : '';
        $id = Db::name('card')->insertGetId($card);
        //图片添加
		if($id){
			$img = input('post.img') ? input('post.img') : '';
			if($img && $img !=''){
				$img = explode(',',input('post.img'));
				for($i=0;$i<count($img);$i++){
					Db::name('picture')->insert(array('user_id'=>$user_id,'card_id'=>$id,'img'=>$img[$i]));
				} 	
			}	
		}
        return hmp(200,'添加成功');
    }

    /**
     * 显示指定的资源
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function read($id)
    {
        $user_id = OnlineUtils::getUserIdBySid();
    	$id = intval(input('id'));
    	$card = Db::name('card')->where('id','eq',$id)->find();
        //查询名片
    	$img = Db::name('picture')->field('concat("'.config('IMG_HEAD').'",img) img')->where('card_id','eq',$id)->select();
        if($card){
            $user = Db::name('users')->where('id','eq',$card['user_id'])->find();
            $card['portrait'] = $user['portrait'];
			$card['img'] = $img;
			//是否点赞
			$click = Db::name('click')->where('user_id','eq',$user_id)->where('card_id','eq',$id)->find();
			if($click){
				$card['is_click'] = 1;
			}else{
				$card['is_click'] = 0;
			}
			//是否收藏
			$collect = Db::name('collect')->where('user_id','eq',$user_id)->where('card_id','eq',$id)->find();
			if($collect){
				$card['is_collect'] = 1;
			}else{
				$card['is_collect'] = 0;
			}
			$card['is_collect'] = 0;
			//浏览+1
			if($card['user_id'] != $user_id){
				Db::name('pv')->insert(array('user_id'=>$user_id,'pv_user_id'=>$card['user_id'],'card_id'=>$id));
				Db::query('update hmp_card set pv = pv + 1 where id = '.$id);
				return hmp(200,'success',['data'=>$card]);
			}else{
				return hmp(200,'success',['data'=>$card]);
			}
        }else{
			return hmp(402,'名片不存在');
		}
    }

    /**
     * 显示编辑资源表单页.
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function edit($id)
    {
        //
    }

    public function updateCard()
    {
        $user_id = OnlineUtils::getUserIdBySid();
        $id = intval(input('post.id'));
        $card['name']         = input('post.name') ? input('post.name') : '';
        $card['phone']        = input('post.phone') ? input('post.phone') : '';
        $card['company_name'] = input('post.company_name') ? input('post.company_name') : '';
        $card['address']      = input('post.address') ? input('post.address') : '';
        $card['email']        = input('post.email') ? input('post.email') : '';
        $card['keyword']      = input('post.keyword') ? input('post.keyword') : '';
        $card['introduce']    = input('post.introduce') ? input('post.introduce') : '';
        $card['module_id']    = input('post.module_id') ? input('post.module_id') : '';
        $card['activity']     = input('post.activity') ? input('post.activity') : '';
        $card['position']     = input('post.position') ? input('post.position') : '';
        $card['wx_number']    = input('post.wx_number') ? input('post.wx_number') : '';
		$card['img_desc']     = input('post.img_desc') ? input('post.img_desc') : '';
        Db::name('card')->where('id','eq',$id)->update($card);
        //删除图片添加新的
        Db::name('picture')->where('card_id','eq',$id)->where('user_id','eq',$user_id)->delete();
        $img = input('post.img') ? input('post.img') : '';
		if($img && $img !=''){
			$img = explode(',',input('post.img'));
			for($i=0;$i<count($img);$i++){
				Db::name('picture')->insert(array('user_id'=>$user_id,'card_id'=>$id,'img'=>$img[$i]));
			}	
		}
        return hmp(200,'success');  
    }

    /**
     * 删除指定资源
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function delete($id)
    {

    }	

    /**
     * [getMyCard 我的名片]
     * @return [type] [description]
     */
    public function getMyCard()
    {
        $id = OnlineUtils::getUserIdBySid();
        $card = Db::name('card')->where('user_id','eq',$id)->find();
    	if($card == false){
    		$card = [];
    	}else{
            $card['portrait'] = config('IMG_HEAD').$card['portrait'];
        }
    	return hmp(200,'success',['data'=>$card]);
    }

    /**
     * [postCard 递名片]
     * @return [type] [description]
     */
    public function postCard()
    {
        $user_id = OnlineUtils::getUserIdBySid();
        // $user_id = intval(input('post.user_id'));
        $card = current(Db::query('select a.id,a.user_id,a.phone,a.company_name,a.address,a.introduce,a.email,a.name,a.position,b.portrait,a.module_id,b.wx_number from hmp_card a left join hmp_users b on a.user_id=b.id where a.user_id='.$user_id.' and b.status=1'));
    	return hmp(200,'success',['data'=>$card]);
    }


	public function deleteCard()
	{
		$user_id = OnlineUtils::getUserIdBySid();
		$id = intval(input('get.id'));
		$card = Db::name('card')->where('id','eq',$id)->where('user_id','eq',$user_id)->where('status','eq',1)->find();
		if($card){
            $card_num = Db::name('card')->where('user_id','eq',$user_id)->count();
            if($card_num > 1){
                Db::query('update hmp_card set status = 2 where id = '.$id);
                return hmp(200,'删除成功');
            }else{
                return hmp(402,'至少需要保留一张名片');
            }
		}else{
			return hmp(402,'名片不存在');
		}
	}

    /**
     * [uploadHeadImg description]
     * @return [type] [description]
     */
    public function uploadImg(Request $request)
    {
        // 获取表单上传文件 例如上传了001.jpg
        $file = request()->file('file');
        // 移动到框架应用根目录/public/uploads/ 目录下
        $info = $file->rule('getDateName')->validate(['ext'=>'jpg,png,gif'])->move(ROOT_PATH . 'public' . DS . 'static/image/');
        if($info){
            // 成功上传后 获取上传信息
            $name = $info->getSaveName();
            $url = config('IMG_HEAD').$name;
            $data['url'] = $url;
            $data['img'] = $name;
            return hmp(200,'success',['data'=>$name,'url'=>$url]);
        }else{
            // 上传失败获取错误信息
            $error = $file->getError();
            return hmp(402,'fail',['data'=>$error]);
        }       
    }

    /**
     * [request description]
     * @param  string  $method [description]
     * @param  [type]  $url    [description]
     * @param  array   $data   [description]
     * @param  boolean $ssl    [description]
     * @return [type]          [description]
     */
    private function _request($method='get',$url,$data=array(),$ssl=true){
            //curl完成，先开启curl模块
            //初始化一个curl资源
            $curl = curl_init();
            //设置curl选项
            curl_setopt($curl,CURLOPT_URL,$url);//url
            //请求的代理信息
            $user_agent = isset($_SERVER['HTTP_USER_AGENT'])?$_SERVER['HTTP_USER_AGENT']:'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:38.0) Gecko/20100101 Firefox/38.0 FirePHP/0.7.4';
            curl_setopt($curl,CURLOPT_USERAGENT,$user_agent);
            //referer头，请求来源        
            curl_setopt($curl,CURLOPT_AUTOREFERER,true);
            curl_setopt($curl, CURLOPT_TIMEOUT, 30);//设置超时时间
            //SSL相关
            if($ssl){
                //禁用后，curl将终止从服务端进行验证;
                curl_setopt($curl,CURLOPT_SSL_VERIFYPEER,false);
                //检查服务器SSL证书是否存在一个公用名
                curl_setopt($curl,CURLOPT_SSL_VERIFYHOST,2);
            }
            //判断请求方式post还是get
            if(strtolower($method)=='post') {
                /**************处理post相关选项******************/
                //是否为post请求 ,处理请求数据
                curl_setopt($curl,CURLOPT_POST,true);
                curl_setopt($curl,CURLOPT_POSTFIELDS,$data);
            }
            //是否处理响应头
            curl_setopt($curl,CURLOPT_HEADER,false);
            //是否返回响应结果
            curl_setopt($curl,CURLOPT_RETURNTRANSFER,true);
            
            //发出请求
            $response = curl_exec($curl);
            if (false === $response) {
                echo '<br>', curl_error($curl), '<br>';
                return false;
            }
            //关闭curl
            curl_close($curl);
            return $response;
    }


    //获取access_token,并保存到文件里
    public function getAccessToken($token_file = ROOT_PATH.'public'.DS.'/access_token'){
        //考虑这个access_token是否过期
        $life_time = 7200;
        //文件存在，并且左后修改时间与当前时间的差小于access_token的有效期，则有效
        if(file_exists($token_file) && time()-filemtime($token_file)<$life_time){
            //得到内容
            return file_get_contents($token_file);
        }
        $appid = config('APPID');
        $appsecret = config('SECRET');
        $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$appid."&secret=".$appsecret;
        //向该地址发送get请求
        $result = $this->_request('get',$url);
        //处理响应结果
        if(!$result){
            return false;
        }
        //存在返回响应结果,返回对象
        $result_obj = json_decode($result);        
        //写入文件
        file_put_contents($token_file, $result_obj->access_token);
        return $result_obj->access_token;
    }    

    //标识qrcodeticket的类型，是永久还是临时
    const QRCODE_TYPE_TEMP = 1;
    const QRCODE_TYPE_LIMIT = 2;
    const QRCODE_TYPE_LIMIT_STR = 3;
    //根据access_token获取ticket
    //@param $content 内容
    //@param $type qr码类型
    //@param $expire 有效期，如果是临时类型需指定
    //@return string ticket 
    public function getQRCodeTicket($content,$type=2,$expire=604800){
        $access_token = $this->getAccessToken();
        $url = 'https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token='.$access_token;
        $type_list = array(
                self::QRCODE_TYPE_TEMP => 'QR_SCENE',
                self::QRCODE_TYPE_LIMIT=> 'QR_LIMIT_SCENE',
                self::QRCODE_TYPE_LIMIT_STR=>'QR_LIMIT_STR_SCENE'
            );
        $action_name = $type_list[$type];
        //post发送的数据
        switch ($type){
            case self::QRCODE_TYPE_TEMP:
                $data_arr['expire_seconds']=$expire;
                $data_arr['action_name'] = $action_name;
                $data_arr['action_info']['scene']['scene_id']=$content;
                break;
            case self::QRCODE_TYPE_LIMIT:
                $data_arr['action_name'] = $action_name;
                $data_arr['action_info']['scene']['scene_id'] = $content;
                break;
            case self::QRCODE_TYPE_LIMIT_STR:
                $data_arr['action_name'] = $action_name;
                $data_arr['action_info']['scene']['scene_str'] = $content;
                break;
        }
        $data = json_encode($data_arr);
        $result = $this->_request('post',$url,$data);
        if(!$result){
            return false;
        }
        $result_obj = json_decode($result);
        return $result_obj;
    }

    //根据ticket获取二维码
    /**
      * @param int|string $content qrcode内容标识
      * @param [type] $file 存储为文件的地址，如果null直接输出
      * @param integer $type 类型
      * @param integer $expire 如果是临时，标识有效期
      * @return  [type]     
     */
    
    public function getQRCode($content,$file=NULL,$type=2,$expire=604800){
        //获取ticket
        $ticket = $this->getQRCodeTicket($content,$type=2,$expire=604800);
        $url = "https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=".$ticket;
        //发送，取得图片数据
        $result = $this->_request('get',$url);
        if($file){
            file_put_contents($file,$result);
        }else{
            return $result;
        }        
    }

}